package cn.iocoder.yudao.module.of.job;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.quartz.core.scheduler.SchedulerManager;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
import cn.iocoder.yudao.module.infra.dal.dataobject.job.JobDO;
import cn.iocoder.yudao.module.infra.dal.mysql.job.JobMapper;
import cn.iocoder.yudao.module.infra.service.job.JobService;
import cn.iocoder.yudao.module.infra.websocket.message.DemoReceiveMessage;
import cn.iocoder.yudao.module.of.dal.dataobject.schedulecenter.ScheduleCenterDO;
import cn.iocoder.yudao.module.of.dal.dataobject.schedulepart.SchedulePartDO;
import cn.iocoder.yudao.module.of.dal.dataobject.userremindsetup.UserRemindSetupDO;
import cn.iocoder.yudao.module.of.dal.mysql.schedulecenter.ScheduleCenterMapper;
import cn.iocoder.yudao.module.of.dal.mysql.schedulepart.SchedulePartMapper;
import cn.iocoder.yudao.module.of.dal.mysql.userremindsetup.UserRemindSetupMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.notify.NotifyMessageDO;
import cn.iocoder.yudao.module.system.dal.mysql.notify.NotifyMessageMapper;
import cn.iocoder.yudao.module.system.service.holiday.HolidayService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;


/**
 * 物理删除 N 天前的任务日志的 Job
 *
 * @author j-sentinel
 */
@Slf4j
@Component
public class ScheduleRemindJob implements JobHandler {


    @Resource
    private SchedulerManager schedulerManager;
    @Resource
    private WebSocketMessageSender webSocketMessageSender;
    @Resource
    private HolidayService holidayService;
    @Resource
    private JobService jobService;
    @Resource
    private JobMapper jobMapper;

    @Resource
    private NotifyMessageMapper notifyMessageMapper;

    @Resource
    private ScheduleCenterMapper scheduleCenterMapper;

    @Resource
    private SchedulePartMapper schedulePartMapper;

    @Resource
    private UserRemindSetupMapper userRemindSetupMapper;

    @Override
    @TenantIgnore
    public String execute(String jobId,String param) {

        log.info("[execute][ ScheduleRemind1Job 参数({}) 个]", param);
        log.info("[execute][ jobId ({}) 个]", jobId);
        LocalDate now = LocalDate.now();

            try {
                if(StringUtils.isNotBlank(param)){
                    JSONObject jsonObject = JSONObject.parseObject(param);
                    Integer repeatPeriod = jsonObject.getInteger("repeatPeriod");
                    // 2： 每天提醒  6：每个工作日提醒
                    if(repeatPeriod ==6){
                        boolean workDay = holidayService.isWorkDay(now);
                        if(!workDay){
                            log.info(now + " 是休息日。 ");
                            return "执行完毕";
                        }
                    }
                }
            } catch (Exception e) {
               // e.printStackTrace();
            }
            JobDO jobDO = jobMapper.selectById(jobId);
            if(jobDO == null){
                return "任务不存在";
            }
            //发送消息
           sendMessage(jobId);


        return String.format("ScheduleRemindJob 执行完毕");
    }

    //            if (message.getToUserId() != null) {
    //                DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(fromUserId)
    //                        .setText(message.getText()).setSingle(true);
    //                webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), message.getToUserId(), // 给指定用户
    //                        "demo-message-receive", toMessage);
    //                return;
    //            }
    // 情况二：群发
    //        DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(185L)
    //                .setText(jobDO.getName()).setSingle(false);
    //        webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), // 给所有用户
    //                "demo-message-receive", toMessage);
    //        log.info("[execute][ ScheduleRemind1Job {} ]", jobId);

    private void sendMessage(String jobId){
        List<ScheduleCenterDO> scheduleCenterDOS = scheduleCenterMapper.selectList(ScheduleCenterDO::getJobId, jobId);
        if(scheduleCenterDOS.isEmpty()){
            return;
        }
        //根据JobID获取日程中心
        ScheduleCenterDO scheduleCenterDO = scheduleCenterDOS.get(0);
        //根据日程中心 获取参与者
        List<SchedulePartDO> schedulePartDOS = schedulePartMapper.selectList(SchedulePartDO::getScId, scheduleCenterDO.getId());

        for(SchedulePartDO part:schedulePartDOS){
            UserRemindSetupDO userRemindSetupDO = userRemindSetupMapper.selectOne(UserRemindSetupDO::getUserId, part.getUserId(),
                    UserRemindSetupDO::getScheduleCategory, scheduleCenterDO.getCategory());
            //没有设置提示提醒，获取设置了提醒，则发消息
            String text = scheduleCenterDO.getTitle();
            if(userRemindSetupDO == null || userRemindSetupDO.getIsRemind() ){
                //发送消息
                DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(185L)
                        .setText(text).setSingle(true);
                webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), part.getUserId(), // 给指定用户
                        "demo-message-receive", toMessage);
                //插入已发送的消息
                NotifyMessageDO notifyMessageDO = new NotifyMessageDO();
                notifyMessageDO.setUserType(2);
                notifyMessageDO.setTemplateContent(text);
                notifyMessageDO.setTemplateNickname("系统消息");
                notifyMessageDO.setTemplateType(1);
                notifyMessageDO.setUserId(part.getUserId());
                notifyMessageDO.setReadStatus(Boolean.FALSE);
                notifyMessageMapper.insert(notifyMessageDO);
            }
        }
    }

}
